package fr.jade.fraclite.orb;

import java.util.HashMap;
import java.util.Map;

import org.jgroups.Channel;
import org.jgroups.JChannelFactory;
import org.objectweb.fractal.api.Interface;
import org.objectweb.fractal.api.type.InterfaceType;

import fr.jade.fraclite.orb.api.Binder;
import fr.jade.fraclite.orb.api.Name;
import fr.jade.fraclite.orb.io.FHAMarshaller;
import fr.jade.fraclite.orb.jgroups.RpcDispatcher;
import fr.jade.fraclite.orb.names.JGroupsName;

/**
 * 
 * @author <a href="mailto:florent.metral@inrialpes.fr">Florent Metral
 *
 */
public class MulticastSkeleton implements Skeleton {
  private JChannelFactory factorySkeleton = null;
  Channel channel = null;
  FHAMarshaller m;
	Map<Long, Object> targets = null;
	Binder binder;
	String groupId;
	
	public MulticastSkeleton(Binder binder){
	  this.binder = binder;
		this.targets = new HashMap<Long, Object>();;
		this.factorySkeleton = new JChannelFactory();
		m = new FHAMarshaller(binder);
    try {
      factorySkeleton.setMultiplexerConfig("stacks.xml");
    } catch (Exception e) {
      e.printStackTrace();
    }
	}

	@Override
  public void registerTarget(Object target) {
	  Long itfId = ((Interface)target).getFcItfGUId();
	  groupId = itfId.toString();
	  
	  try {
      //channel = factorySkeleton.createMultiplexerChannel("udp", itfId.toString());
	    channel = factorySkeleton.createChannel("udp");
      RpcDispatcher disp = new RpcDispatcher(channel, null, null, target);
      
      disp.setMarshaller(m);
      disp.setResponseMarshaller(m);
      disp.setRequestMarshaller(m);

      System.out.println("[skel] connect "+groupId);
      channel.connect(groupId);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
	
	@Override
  public Name getName(Object target) {
	  long itfId = ((Interface)target).getFcItfGUId();
    String signature = ((InterfaceType)((Interface)target).getFcItfType()).getFcItfSignature();
    return new JGroupsName(itfId, signature, binder, groupId);
  }
	
	@Override
	public void run() {

	}


  

}
